// pages/login/login.js
var userUtils = require("../../utils/user.js");
const { getUserInfo } = require('../../utils/user')
const validate = require('../../utils/validate')
const common = require('../../utils/common')
const authServices = require('../../services/auth')

Page({
  data: {
    userInfo: null,
    submitInfo: {
      phone: '',
      code: '',
      score: 0,
      isPhone: false,
      isLoginEnable: false
    },
  },
  onLoad: function (options) {
    wx.hideShareMenu();
    this.initData(options);
  },

  //初始化数据
  initData: function (options) {
    let submitInfo = this.data.submitInfo;
    let phone = options.phone;
    if (phone) {
      submitInfo = { ...submitInfo, ...{ phone, isPhone: true } }
    }
    this.setData({
      userInfo: getUserInfo(),
      submitInfo: submitInfo
    });
  },
  //其他方式-获取微信手机号码
  onGetPhoneNumber: function (e) {
    var denied = e.detail.errMsg.indexOf("fail user deny") != -1
    if (denied) return
    //解析获取到的手机号码
    this.requestToDecryptMobile(e.detail)
  },

  //解析手机号码
  requestToDecryptMobile: function (res) {
    wx.navigateTo({ url: '/pages/index/index' })
    const data = {
      encryptedData: res.encryptedData,
      iv: res.iv
    }
    authServices.decryptMobile(data).then(res => {
      const loginData = {
        code: this.data.userInfo.code,
        loginType: 1,
        mobile: res.data,
        nickname: this.data.userInfo.wxUserInfo.nickName,
        openId: this.data.userInfo.openId,
        profilePhoto: this.data.userInfo.wxUserInfo.avatarUrl,
        sex: this.data.userInfo.wxUserInfo.gender,
        smsCode: "",
        unionId: ""
      }
      return authServices.doLogin(loginData);
    }).then(res => {
      userUtils.updateUserInfo({ userInfo: res.data });
      wx.navigateTo({ url: '/pages/index/index' })
    }).catch(err => {
      common.log(err);
    });
  },
})